package com.meitutest.autoscript.utils;

import android.graphics.Point;
import android.support.test.uiautomator.UiDevice;
import android.text.TextUtils;

/**
 * 长按
 */

public class LongpressEvent {
    private static final String MEITU_MENU_KEY = "aw9136_ts";


    /**
     * 获取Menu键对应的x,y坐标
     *
     * @return 坐标，如果解析失败，则返回null
     */
    private static Point getMenuPoint(UiDevice uiDevice) {

        String cmd = "cat /sys/board_properties/virtualkeys." + MEITU_MENU_KEY;
        String rs = CMDUtils.runCmdByDevice(uiDevice, cmd);
        if (!TextUtils.isEmpty(rs)) {
            String temp[] = rs.split(":");
            Point p = new Point();
            p.x = Integer.parseInt(temp[2]);
            p.y = Integer.parseInt(temp[3]);
            return p;
        } else {
            return null;
        }

    }

    /**
     * 获取按下Menu键对应的事件
     *
     * @return 对应的事件, 如果解析失败，则返回null
     */
    private static String getMenuEvent(UiDevice uiDevice) {
        String cmd = "cat /proc/bus/input/devices";
        String rs = CMDUtils.runCmdByDevice(uiDevice, cmd);
        if (!TextUtils.isEmpty(rs)) {
            String temp[] = rs.split("\n");
            for (int i = 0; i < temp.length; i++) {
                if (temp[i].contains(MEITU_MENU_KEY)) {
                    String code = temp[i + 2].substring(temp[i + 2].length() - 1);
                    return "event" + code;
                }
            }
        }
        return null;
    }

    /**
     * 仅适用于美图手机，其他机型未适配
     */
    public static void longPressMenu(UiDevice uiDevice) {
        String eventCode = getMenuEvent(uiDevice);
        Point point = getMenuPoint(uiDevice);

        //如果解析不到相关的数据，则使用input命令实现
        if (TextUtils.isEmpty(eventCode) || point == null) {
            String others = "input keyevent --longpress 82";
            CMDUtils.runCmdByDevice(uiDevice, others);
            return;
        }

        String contentList[] = {
                "sendevent /dev/input/" + eventCode + " 3 0 " + point.x,
                "sendevent /dev/input/" + eventCode + " 3 1 " + point.y,
                "sendevent /dev/input/" + eventCode + " 1 330 1",
                "sendevent /dev/input/" + eventCode + " 0 0 0",
                "sleep 2 ",
                "sendevent /dev/input/" + eventCode + " 0 0 0",
                "sendevent /dev/input/" + eventCode + " 1 330 0",
                "sendevent /dev/input/" + eventCode + " 0 0 0 "
        };
        for (String aContentList : contentList) {
            CMDUtils.runCmdByDevice(uiDevice, aContentList);
        }
    }
}
